<template>
  <div class="cart">
    <div class="container cart-frame">
      <div class="page-title">
        <p class="title">MY BAG</p>
        <span class="cart-tips">{{ cartList.length }} ITEMS</span>
        <div class="icon"></div>
      </div>
      <div class="product-frame" v-for="(item, index) in cartList" :key="index">
        <div class="product-img">
          <van-image class="img" fit="cover" lazy-load :src="item.pic" />
        </div>
        <div class="product-main">
          <div class="type-frame">
            <p class="product-title">
              {{ item.title }}
            </p>
            <p class="product-type">
              <span v-if="item.status">{{ item.attribute_me }}</span>
              <span v-else style="color: red">Please reselect the product</span>
            </p>
          </div>
          <div class="product-info" @click="clickNumber(index)">
            <p class="product-price">${{ item.price }}</p>
            <van-stepper
              :value="item.number"
              async-change
              @change="changeNumber"
              button-size="1rem"
            />
            <span class="ac-bg co-light" @click="deletePro(index)">Remove</span>
          </div>
        </div>
      </div>
      <Loading v-if="loading" />
      <Nodata v-if="cartList.length == 0 && !loading" />
      <div class="tips-frame" v-if="!loading">
        <p>Subtotal</p>
        <p class="price">${{ totalPrice }}</p>
      </div>
      <div
        class="btn-frame"
        v-if="cartList.length > 0"
        @click="clickCheckOrder"
      >
        CHECK OUT
      </div>
      <img
        @click="clickPaymethods"
        src="@/assets/imgs/cart-footer.png"
        class="img-fluid"
      />
    </div>
  </div>
</template>
<script>
import tool from "@/common/tool.js";
export default {
  data() {
    return {
      loading: false,
      numberIndex: 0,
      isChange: false,
      totalPrice: 0,
    };
  },
  computed: {
    cartRefresh() {
      //购物车刷新
      return this.$store.state.menu.cartRefresh;
    },
    cartList() {
      //购物车列表
      return this.$store.state.menu.cartList;
    },
  },
  activated() {
    if (this.Login) {
      this.getCartList();
    } else {
      this.controPrice();
    }
  },
  watch: {
    cartList(list) {
      if (list) {
        this.controPrice();
      }
    },
  },
  methods: {
    //跳转底部文案支付方式
    clickPaymethods() {
      this.$router.push("/other/deliorder/paymethod");
    },
    //获取购物车列表,刷新购物车列表
    async getCartList() {
      this.loading = true;
      this.cartList = [];
      let res = await this.$store.dispatch("menu/cartList", {
        r: Math.random(),
      }); //加随机数防止请求被缓存不刷新列表
      if (res.code == 0 && res.data != undefined) {
        let cartList = res.data;
        let totalPrice = 0;
        for (let i = 0; i < cartList.length; i++) {
          cartList[i].number = parseInt(cartList[i].number);
          cartList[i].price = parseFloat(cartList[i].price);
          cartList[i]["attribute_me"] = cartList[i].attribute_text
            .toString()
            .replaceAll(",", ";");
          totalPrice += cartList[i].price * cartList[i].number;
        }
        this.$store.commit("menu/setCartRefresh", false); //取消刷新
        this.$store.commit("menu/setCartList", cartList);
        this.totalPrice = totalPrice;
      }
      this.loading = false;
    },
    //计算总价
    controPrice() {
      let totalPrice=0;
      for (let i = 0; i < this.cartList.length; i++) {
        this.cartList[i].number = parseInt(this.cartList[i].number);
        this.cartList[i].price = parseFloat(this.cartList[i].price);
        totalPrice += this.cartList[i].price * this.cartList[i].number;
      }
      this.totalPrice=totalPrice;
    },
    //删除购物车商品
    async deletePro(index) {
      this.tips.startLoadingToast();
      if (this.Login) {
        let res = await this.$store.dispatch("menu/changeProduct", {
          id: this.cartList[index].id,
          aid: this.cartList[index].aid,
          number: 0,
        });
        this.tips.closeToast();
        this.isChange = false;
        if (res.code == 0) {
          this.cartList.splice(index, 1);
          this.$store.commit("menu/setCartList", this.cartList);
          let totalPrice = 0;
          for (let i = 0; i < this.cartList.length; i++) {
            totalPrice += this.cartList[i].price * this.cartList[i].number;
          }
          this.totalPrice = totalPrice;
        } else {
          this.$toast.fail(res.msg);
        }
      } else {
        this.cartList.splice(index, 1);
        let totalPrice = 0;
        for (let i = 0; i < this.cartList.length; i++) {
          totalPrice += this.cartList[i].price * this.cartList[i].number;
        }
        this.totalPrice = totalPrice;
        this.$store.commit("menu/setCartList", this.cartList);
        tool.setStorage("cartList", this.cartList);
        setTimeout(() => {
          this.tips.closeToast();
        }, 1000);
      }
    },
    //点击number时的索引
    clickNumber(index) {
      this.numberIndex = index;
      this.isChange = true;
    },
    //改变数量
    async changeNumber(value) {
      this.tips.startLoadingToast();
      console.log(value);
      setTimeout(async () => {
        if (this.isChange) {
          if (this.Login) {
            let res = await this.$store.dispatch("menu/changeProduct", {
              id: this.cartList[this.numberIndex].id,
              aid: this.cartList[this.numberIndex].aid,
              number: value,
            });
            this.tips.closeToast();
            this.isChange = false;
            if (res.code == 0) {
              this.cartList[this.numberIndex].number = value;
              this.$store.commit("menu/setCartList", this.cartList);
              let totalPrice = 0;
              for (let i = 0; i < this.cartList.length; i++) {
                totalPrice += this.cartList[i].price * this.cartList[i].number;
              }
              this.totalPrice = totalPrice;
            } else {
              this.$toast.fail(res.msg);
            }
          } else {
            let totalPrice = 0;
            for (let i = 0; i < this.cartList.length; i++) {
              totalPrice += this.cartList[i].price * this.cartList[i].number;
            }
            this.tips.closeToast();
            this.cartList[this.numberIndex].number = value;
            this.totalPrice = totalPrice;
            this.$store.commit("menu/setCartList", this.cartList); //保存购物车列表
            tool.setStorage("cartList", this.cartList);
          }
        }
      }, 300);
    },
    //立即结算
    clickCheckOrder() {
      this.tips.startLoadingToast();
      let proList = [];
      for (let i = 0; i < this.cartList.length; i++) {
        if (this.cartList[i].status) {
          proList.push(this.cartList[i]);
        }
      }
      this.$store.commit("order/setRefreshPro", true);
      tool.setStorageAsyn("cartCheckList", proList, () => {
        setTimeout(() => {
          this.$router.push({
            path: "/user/order/checkorder",
          });
          this.tips.closeToast();
          this.$store.commit("menu/setCartList", []);
          tool.setStorage("cartList", []);
        }, 1000);
      });
    },
  },
};
</script>
<style lang="less" scoped>
@import "./cart.less";
</style>